package org.ucas.faker.web.utils.mql.parse;


import org.ucas.faker.web.utils.mql.domain.Where;

public class FieldTreeVisitor extends MqlBaseVisitor<Where> {

  private MqlParser.WordExprContext right;

  private MqlParser.CondContext parent;


  public FieldTreeVisitor(MqlParser.WordExprContext right, MqlParser.CondContext parent) {
    this.right = right;
    this.parent = parent;
  }

  @Override
  public Where visitAndFieldExpr(MqlParser.AndFieldExprContext ctx) {
    Where res = new Where(Where.CONN.AND);
    ctx.fieldExpr().forEach(c -> {
      Where cond = visit(c);
      if (cond == null) return;
      if (cond.getBoost() != null) {
        res.setBoost(res.getBoost() == null ? cond.getBoost() : Math.max(res.getBoost(), cond.getBoost()));
      }
      res.addWhere(cond);
    });
    return res;
  }

  @Override
  public Where visitIdFieldExpr(MqlParser.IdFieldExprContext ctx) {
    WordTreeVisitor visitor = new WordTreeVisitor(ctx, parent);
    return visitor.visit(right);
  }

  @Override
  public Where visitParFieldExpr(MqlParser.ParFieldExprContext ctx) {
    return visit(ctx.fieldExpr());
  }

  @Override
  public Where visitOrFieldExpr(MqlParser.OrFieldExprContext ctx) {
    Where res = new Where(Where.CONN.OR);
    ctx.fieldExpr().stream().forEach(c -> {
      Where cond = visit(c);
      if (cond == null) return;
      if (cond.getBoost() != null) {
        res.setBoost(res.getBoost() == null ? cond.getBoost() : Math.max(res.getBoost(), cond.getBoost()));
      }
//      cond.setConn(Where.CONN.OR);
      res.addWhere(cond);
    });
    return res;
  }

  @Override
  public Where visitNotFieldExpr(MqlParser.NotFieldExprContext ctx) {
    Where res = new Where(Where.CONN.NOT);
    Where cond = visit(ctx.fieldExpr());
    res.addWhere(cond);
    res.setBoost(cond.getBoost());
    return res;
  }
}
